import React, { useMemo, useState, useEffect } from 'react';
import { Icon, Modal, Spin } from 'antd';
import UploadOss from '@/components/UploadOss';
import defaultUploadAvatar from '@/assets/defaultUploadAvatar.png';
import styles from './index.less';

interface IFile {
    keyName: string;
    name: string;
    uid: string;
    url: string;
}

type Props = {
    categoryCode: string;
    maxFileSize?: number;
    fileExtensions?: string;
    value: {
        allFileList: Array<IFile>;
        uploadResourceFile: Object;
    };
    onChange: Function;
};

/**
 * 头像上传组件
 */
const UploadAvatar = React.forwardRef(
    ({ categoryCode, maxFileSize = 10, fileExtensions = 'png,jpg,jpeg', value, onChange }: Props, ref) => {
        const [avatar, setAvatar] = useState('');
        const [previewVisible, setPreviewVisible] = useState(false);
        const [isUploaded, setIsUploaded] = useState(false);
        const { allFileList = [], uploadResourceFile } = value || {};
        const [previewUrl, setPreview] = useState('');
        const [isLoading, setIsLoading] = useState(false);

        useEffect(() => {
            if (allFileList.length >= 1) {
                const { url } = allFileList[0];
                if (url) {
                    setAvatar(url);
                }
                setIsUploaded(true);
            } else {
                setAvatar('');
                setIsUploaded(false);
            }
        }, [allFileList]);

        const maxFileSizeErrorMsg = useMemo(() => `文件大小不能超过${maxFileSize}MB！`, [maxFileSize]);
        const fileTypeErrorMsg = useMemo(() => `只能上传${fileExtensions}格式的文件！`, [fileExtensions]);

        const handleChanged = (showFileList = [], uploadResource) => {
            const isFileUploading = showFileList.filter(item => item.status === 'uploading').length > 0;
            setIsLoading(isFileUploading);
            onChange({
                allFileList: showFileList,
                uploadResourceFile: uploadResource
            });
        };

        const handleDeleteAvatar = () => {
            onChange({
                allFileList: [],
                uploadResourceFile: null
            });
        };

        const handleTransformFile = file => {
            setPreview(window.URL.createObjectURL(file));
            return Promise.resolve(file);
        };

        return (
            <div ref={ref as React.RefObject<HTMLDivElement>} className={styles.uploadAvatarWrapper}>
                <UploadOss
                    dragAble={false}
                    categoryCode={categoryCode}
                    checkFileSize={maxFileSize}
                    uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                    checkFileTypeMsg={fileTypeErrorMsg}
                    checkFileType={fileExtensions}
                    checkFileSizeMsg={maxFileSizeErrorMsg}
                    uploadResource={uploadResourceFile}
                    sysCode="OA"
                    businessCode="SysRule"
                    fileList={allFileList}
                    setFileList={handleChanged}
                    onUploaded={() => setAvatar(previewUrl)}
                    {...{ disabled: isUploaded, multiple: false, transformFile: handleTransformFile }}
                >
                    <div className={styles.uploadAvatar}>
                        <div
                            className={styles.avatar}
                            style={{ backgroundImage: `url(${avatar || defaultUploadAvatar})` }}
                        >
                            {isLoading && <Spin className={styles.uploading} size="small" />}
                            {isUploaded && avatar && (
                                <div className={styles.uploadedAvatar}>
                                    <Icon type="eye" onClick={() => setPreviewVisible(true)} />
                                    <Icon type="delete" onClick={handleDeleteAvatar} />
                                </div>
                            )}
                        </div>
                        <div className={styles.uploadButton}>
                            <Icon type="plus" />
                            上传证件照
                        </div>
                    </div>
                </UploadOss>
                <Modal visible={previewVisible} footer={null} onCancel={() => setPreviewVisible(false)}>
                    <img alt="example" style={{ width: '100%' }} src={avatar} />
                </Modal>
            </div>
        );
    }
);

export default UploadAvatar;
